package com.disc.heike;

import com.disc.baidu.BaiduUser;
import com.disc.common.Constant;
import com.disc.common.DiscResponse;
import com.disc.util.HttpUtil;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HeiKeLogin {

    public CookieStore cookieStore =  new BasicCookieStore();

    public CloseableHttpClient httpclient;

    public String type = "KEYKE";

    private String __EVENTTARGET;

    private String __EVENTARGUMENT;

    private String __VIEWSTATE;

    private String __EVENTVALIDATION;

    //BT文件
    private String ctl00$ContentPlaceHolder1$FileOpenTorrent;

    //磁力链接
    private String ctl00$ContentPlaceHolder1$txtBtHash = "magnet:?xt=urn:btih:4d6a644e61c918947a97846d65038965d81ffeae";
    //这个应该是一个标识（默认值为 “解析”）
    private String ctl00$ContentPlaceHolder1$btnGoHash;
    //搜索内容
    private String ctl00$ContentPlaceHolder1$txtSearchName;

    /**
     * 初始化httpclient
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public  HeiKeLogin() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException
    {
        httpclient =  HttpClients.custom().useSystemProperties().setConnectionManager(HttpUtil.getSSLNoCheckConnectionManager()).setDefaultCookieStore(cookieStore).build();
    }

    /**
     * 初始化cookie 获取登录时需要的参数
     */
    public Map<String,String> initCookie()
    {
      String result =  HttpUtil.createHttpGet(Constant.HEIKE_INIT_COOKIE_URL,httpclient);
      Document mainDocument  = Jsoup.parse(result);
      Map<String,String> resultMap = new HashMap<>();
      resultMap.put("__VIEWSTATE",mainDocument.select("input[name=__VIEWSTATE]").val());
      resultMap.put("__EVENTVALIDATION",mainDocument.select("input[name=__EVENTVALIDATION]").val());
      return resultMap;
    }

    public byte[] getVcodeImage()
    {
        return  HttpUtil.createHttpGetInputStream(Constant.HEIKE_VOODE_URL,httpclient);
    }

    public DiscResponse login(BaiduUser user,Map<String,String> resultMap)
    {
        DiscResponse discResponse = new DiscResponse();
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("__VIEWSTATE",resultMap.get("__VIEWSTATE")));
        nvps.add(new BasicNameValuePair("__EVENTVALIDATION",resultMap.get("__EVENTVALIDATION")));
        nvps.add(new BasicNameValuePair("txtId",user.getAccount()));
        nvps.add(new BasicNameValuePair("txtPwd",user.getPassword()));
        nvps.add(new BasicNameValuePair("txtCode",user.getVerificationCode()));
        nvps.add(new BasicNameValuePair("btnLogin","登   录"));
        String result =  HttpUtil.createHeikeLoginHttpPost(Constant.HEIKE_INIT_COOKIE_URL,nvps,httpclient);
        if("/Main.aspx".equals(result))
        {
            String resultHtml =  HttpUtil.createHttpGet(Constant.HEIKE_LOGIN_SUCCESS,httpclient);
            Document mainDocument  = Jsoup.parse(resultHtml);
            __EVENTTARGET = mainDocument.select("input[name=__EVENTTARGET]").val();
            __EVENTARGUMENT = mainDocument.select("input[name=__EVENTARGUMENT]").val();
            __VIEWSTATE = mainDocument.select("input[name=__VIEWSTATE]").val();
            __EVENTVALIDATION = mainDocument.select("input[name=__EVENTVALIDATION]").val();
            ctl00$ContentPlaceHolder1$btnGoHash = mainDocument.select("input[name=ctl00$ContentPlaceHolder1$btnGoHash]").val();
            analysisMagneticForceUrl();
            discResponse.setCode("0");
            discResponse.setMessage("登录成功！");
        }else
        {
            discResponse.setCode("-1");
            discResponse.setMessage("登录失败！");
        }
        return discResponse;
    }

    public void analysisMagneticForceUrl()
    {
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("__EVENTTARGET",__EVENTTARGET));
        nvps.add(new BasicNameValuePair("__EVENTARGUMENT",__EVENTARGUMENT));
        nvps.add(new BasicNameValuePair("__VIEWSTATE",__VIEWSTATE));
        nvps.add(new BasicNameValuePair("__EVENTVALIDATION",__EVENTVALIDATION));
        nvps.add(new BasicNameValuePair("__EVENTVALIDATION",__EVENTVALIDATION));
        //nvps.add(new BasicNameValuePair("ctl00$ContentPlaceHolder1$FileOpenTorrent",null));
        nvps.add(new BasicNameValuePair("ctl00$ContentPlaceHolder1$btnGoHash",ctl00$ContentPlaceHolder1$btnGoHash));
        nvps.add(new BasicNameValuePair("ctl00$ContentPlaceHolder1$txtSearchName",""));
       String  result = HttpUtil.createHeikeAnalysisHttpPost(Constant.HEIKE_LOGIN_SUCCESS,nvps,httpclient);
       System.out.println(result);
    }
}
